<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Article;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Config;
use App\Models\FriendshipLink;
use App\Models\Nav;
use App\Models\Tag;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
         // 如果表不存在则不再向下执行
        try {
            // 获取配置项
            $config = Config::where('id', '>', 100)->pluck('value', 'name');
        } catch (Exception $exception) {
            return;
        }
           // 动态替换 /config 目录下的配置项
        config($config->toArray());

        // 获取各种统计
        view()->composer(['layouts/home', 'admin/index/index'], function ($view) {
            $articleCount = Article::count('id');
            $commentCount = Comment::count('id');
          //  $chatCount = Note::count('id');

            // 分配数据
            $assign = compact('articleCount', 'commentCount');
            $view->with($assign);
        });
        
        view()->composer(['admin/config/*'], function ($view) use ($config) {
            $assign = compact('config');
            $view->with($assign);
        });
         //分配前台通用的数据
        view()->composer('layouts/home', function ($view)  {
            $category = Category::select('id', 'name', 'slug')->orderBy('sort')->get();
            $tag = Tag::has('articles')->withCount('articles')->get();

            $topArticle = Article::select('id', 'title', 'slug')
                ->where('is_top', 1)
                ->orderBy('created_at', 'desc')
                ->get();

            $friendshipLink = FriendshipLink::select('name', 'url')
                ->orderBy('sort')
                ->get();

            $nav = Nav::select('name', 'url')
                ->orderBy('sort')
                ->get();

            // 获取赞赏捐款文章
            $qunArticleId = config('bjyblog.qq_qun.article_id');
            if (empty($qunArticleId)) {
                $qqQunArticle = [];
            } else {
                $qqQunArticle = Article::select('id', 'title')->where('id', $qunArticleId)->first();
            }

       

            $homeFootColNumber = array_filter(config('bjyblog.social_links')) === [] ? 4 : 3;

            // 分配数据
            $assign = compact('category', 'tag', 'topArticle', 'friendshipLink', 'nav', 'qqQunArticle', 'homeFootColNumber');
            $view->with($assign);
        });
        
        view()->composer(['layouts/home', 'admin/index/index'], function ($view) {
            $latestComments = (new Comment())->limit(5)->get();

            $assign = compact('latestComments');
            $view->with($assign);
        });

    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
